<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="productQuery">
                <el-form-item>
                    <el-input v-model="productQuery.name" placeholder="姓名" size="small"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="loadData" size="small">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd" size="small">新增</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="danger" @click="batchOnsale(0)" size="small" :disabled="this.sels.length===0">批量上架</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="danger" @click="batchOnsale(-1)" size="small" :disabled="this.sels.length===0">批量下架</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="products" highlight-current-row v-loading="listLoading"
                  border stripe @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column type="index" width="60"></el-table-column>
            <el-table-column prop="name" label="名称" width="160" ></el-table-column>
            <el-table-column prop="costprice" label="成本价" width="90" ></el-table-column>
            <el-table-column prop="saleprice" label="零售价" width="90" ></el-table-column>
            <el-table-column prop="salecount" label="销量" width="70" ></el-table-column>
            <el-table-column prop="state" label="状态" width="70">
                <template scope="scope">
                    <b style="color: #12d30c;" v-if="scope.row.state==0">上架</b>
                    <b style="color: #d3241e;" v-else>下架</b>
                </template>
            </el-table-column>
            <el-table-column prop="offsaletime" label="下架时间" min-width="120"></el-table-column>
            <el-table-column prop="onsaletime" label="上架时间" min-width="120"></el-table-column>
            <!--<el-table-column prop="shop.name" label="商家店铺" min-width="110"></el-table-column>-->
            <el-table-column label="操作" width="100">
                <!--
                    slot-scope="scope"  表示将当前行的json对象封装到scope变量中
                        可以scope.row来获取当前行的json对象数据
                -->
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--分页工具条-->
        <el-col :span="24" class="toolbar">
            <!--<el-button type="danger" @click="batchRemove" size="small" :disabled="this.sels.length===0">批量删除</el-button>-->
            <!--
                el-pagination 是ElementUI的分页组件
                    layout 布局
                        sizes 每页行数的下拉框
                        prev 上一页按钮
                        next 下一页按钮
                        pager 每一页的快速链接
                        jumper 提供一个输入框，输入一个页码后按回车，直接跳到某一页
                        total 显示总行数
                    current-change 当当前页码发生改变时触发的事件，就是翻页
                    current-page 当前页码
                    page-size 每页行数
                    total 总行数：需要在当前组件中定义一个属性与之绑定，然后页面挂载完毕后加载数据的回调函数中给这个属性赋值
                        elementui就会自动计算总页数
                        总页数 = total%page-size == 0 ? total/page-size : total/page-size + 1
            -->
            <el-pagination layout="prev, pager, next, total" @current-change="handleCurrentChange" :page-size="10" :total="total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--模态框-->
        <el-dialog title="新增/编辑" :visible.sync="dialogFormVisible" custom-class="mydialog" :close-on-click-modal="false">
            <el-form :model="formData" ref="formData" :rules="formDataRules" labelWidth="80px">
                <el-row>
                    <el-col :span="8">
                        <el-form-item prop="name">
                            <el-input v-model="formData.name" auto-complete="off" placeholder="商品/服务项目名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item prop="costprice">
                            <el-input v-model="formData.costprice" auto-complete="off" placeholder="成本价"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item prop="saleprice">
                            <el-input v-model="formData.saleprice" auto-complete="off" placeholder="零售价"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item>
                    <el-upload
                            class="upload-demo"
                            action="http://localhost:8080/fastdfs/uploadFile"
                            :on-remove="handleRemove"
                            :on-success="handleSuccess"
                            :file-list="fileList"
                            list-type="picture">
                        <el-button size="small" type="primary" style="width: 100px;height: 29px;">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="商品描述">
                    <el-upload class="avatar-uploader quill-img" id="quill-img1" style="display: none;"
                               action="http://localhost:8080/fastdfs/uploadFile"
                               :show-file-list="false"
                               :on-success="quillImgSuccess1"
                               accept='.jpg,.jpeg,.png,.gif'>
                    </el-upload>
                    <quill-editor id="intro" ref="intro" v-model="formData.intro" placeholder="商品描述" :options="quillOption"></quill-editor>
                </el-form-item>
                <el-form-item label="下单须知">
                    <el-upload class="avatar-uploader quill-img" id="quill-img2" style="display: none;"
                               action="http://localhost:8080/fastdfs/uploadFile"
                               :show-file-list="false"
                               :on-success="quillImgSuccess2"
                               accept='.jpg,.jpeg,.png,.gif'>
                    </el-upload>
                    <quill-editor id="orderNotice" ref="orderNotice" v-model="formData.orderNotice" placeholder="下单须知" :options="quillOption"></quill-editor>
                </el-form-item>
                <el-input v-model="formData.id" v-show="false"></el-input>
                <el-input v-model="formData.resources" v-show="false"></el-input>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="submit" :loading="submitLoading">提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    import util from '../../common/js/util'
    import { quillEditor } from "vue-quill-editor"; //调用编辑器
    import quillConfig from '../../common/js/quill-config.js'   //导入quill富文本编辑框的配置文件
    import 'quill/dist/quill.core.css';
    import 'quill/dist/quill.snow.css';
    import 'quill/dist/quill.bubble.css';

    export default {
        components: {
            quillEditor         //自定义局部组件 使用导入的vue-quill-editor js内部的组件
        },
        data() {
            return {
                fileList:[],                //el-upload组件上传的文件列表
                quillOption: quillConfig,   //将quill的配置信息定义成当前组件的属性
                productQuery: {          //分页和高级查询的条件参数对象
                    name: '',
                    pageNo: 1,
                    pageSize: 10
                },
                products: [],            //表格数据
                total: 0,                   //分页组件：总行数
                listLoading: false,         //表格数据加载状态
                sels: [],                   //表格中被选中的行
                dialogFormVisible: false,   //模态框界面是否显示
                submitLoading: false,       //表单提交状态
                formDataRules: {            //表单验证规则对象
                    /**
                     * name  表示声明了一个验证规则叫name
                     *  这个验证规则本身是一个json数组，表示当前验证规则内部可以写多个验证
                     *      required：表示是否必填
                     *      message：当你输入的内容不符合当前规则要求的时候，弹出的提示消息
                     *      trigger：触发器，表示什么时候触发当前验证  blur 表示失去焦点
                     *  除了可以验证必填之外，还可以有很多种验证规则：比如字符串长度范围、数字范围、日期、数组
                     */
                    name: [
                        { required: true, message: '请输入部门名称', trigger: 'blur' },
                        //{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
                    ],
                    sn: [
                        { required: true, message: '请输入部门编号', trigger: 'blur' }
                    ],
                    phone: [
                        { required: true, message: '请输入手机号', trigger: 'blur' },
                    ]
                },
                //模态框表单界面数据
                formData: {
                    id: null,
                    name: '',
                    costprice: '',
                    saleprice: '',
                    state: -1,
                    resources: '',
                    detailId: null,         //商品详情id
                    intro:'',               //商品详情介绍
                    orderNotice:''          //下单须知
                },
                fastdfsImgUrls:[],                //fastdfs服务器上面的图片地址数组
            }
        },
        methods: {
            //翻页事件：参数是翻页后的当前页码
            handleCurrentChange(val) {
                this.productQuery.pageNo = val;
                this.loadData();        //使用这个json对象作为请求参数去查询数据
            },
            //获取部门列表
            loadData() {
                this.listLoading = true;        //表格正在加载数据
                //NProgress.start();            //启动进度条
                //发送ajax请求
                this.$http.patch("/product", this.productQuery).then(res => {
                    this.listLoading = false;       //表格加载数据完毕
                    //NProgress.done();         //停止进度条
                    this.products = res.data.list    //给组件属性赋值即可自动展示数据
                    this.total = res.data.total
                })
            },
            //显示编辑界面
            handleEdit(index, row) {
                this.dialogFormVisible = true;
                this.formData = Object.assign({}, row);
                this.formData.intro = this.formData.productDetail.intro
                this.formData.orderNotice = this.formData.productDetail.orderNotice
                this.formData.detailId = this.formData.productDetail.id
                //回填el-upload文件上传框的图片
                let urls = this.formData.resources.split(",")
                //先清空一下this.fileList
                this.fileList = []
                for(let i=0;i<urls.length;i++){
                    let imgName = urls[i].substring(urls[i].lastIndexOf("/") + 1)
                    this.fileList.push({
                        name: imgName,
                        url: urls[i]
                    })
                }
            },
            //显示新增界面
            handleAdd() {
                this.dialogFormVisible = true;
                //先清空一下this.fileList
                this.fileList = []
                this.formData = {
                    id: null,
                    name: '',
                    costprice: '',
                    saleprice: '',
                    state: -1,
                    resources: '',
                    detailId: null,         //商品详情id
                    intro:'',               //商品详情介绍
                    orderNotice:''          //下单须知
                }
            },
            //提交表单
            submit() {
                this.$refs.formData.validate(valid => {
                    if (valid) {
                        //NProgress.start();
                        this.submitLoading = true;              //表单正在提交
                        //封装一下表单参数对象
                        this.formData.productDetail = {
                            id: this.formData.detailId,
                            intro: this.formData.intro,
                            orderNotice: this.formData.orderNotice
                        }
                        //发送请求
                        this.$http.put("/product", this.formData).then(res => {
                            //NProgress.done();
                            this.submitLoading = false;         //表单提交完毕
                            let {success,msg} = res.data        //解构表达式
                            if(success){
                                this.$message.success(msg);
                                this.dialogFormVisible = false  //关闭模态框
                                this.loadData()                 //重新加载表格数据
                            }else{
                                this.$message.error(msg);
                            }
                        })
                    }
                });
            },
            selsChange(sels) {
                this.sels = sels;
            },
            //批量上下架
            batchOnsale(state) {
                var ids = this.sels.map(item => item.id).toString();
                this.$confirm('确认'+(state==0?'上架':'下架')+'选中的商品/服务项目吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    this.$http.get("/product/batchOnsale/"+ids+"/"+state).then(res => {
                        this.listLoading = false;
                        //NProgress.done();
                        let {success,msg} = res.data
                        if(success){
                            this.$message.success(msg)
                            this.loadData();
                        }else{
                            this.$message.error(msg)
                        }
                    })
                })
            },
            //删除图片
            handleRemove(file, fileList){
                console.debug(file.url)
                let imgUrl = file.url.substring(file.url.indexOf("/group"))
                //发送请求到我们后端项目中，后台项目中使用FastDfsUtils工具类来删除fastdfs服务器上面的图片
                this.$http.delete("/fastdfs/deleteFile?filePath="+imgUrl).then(res => {
                    let {success, msg} = res.data
                    if(success){
                        this.$message.success(msg)
                        this.fileList = fileList;
                        this.fastdfsImgUrls = []
                        for(let i=0;i<this.fileList.length;i++){
                            this.fastdfsImgUrls.push(this.fileList[i].url)
                        }
                        this.formData.resources = this.fastdfsImgUrls.join(",")
                    }else{
                        this.$message.error(msg)
                    }
                })
            },
            //上传成功
            handleSuccess(response, file, fileList){
                let url = 'http://121.37.194.36'+response.data
                this.fastdfsImgUrls.push(url)
                this.formData.resources = this.fastdfsImgUrls.join(",")
                console.debug(this.formData.resources)
            },
            //商品描述 富文本编辑框图片上传
            quillImgSuccess1(res, file) { // 获取富文本组件实例
                let quill = this.$refs.intro.quill;
                // 如果上传成功
                if (res.success) {
                    // 获取光标所在位置
                    let length = quill.getSelection().index;
                    // 插入图片 res.data为服务器返回的图片地址
                    quill.insertEmbed(length, 'image', 'http://121.37.194.36'+res.data);// 这里的url是图片的访问路径不是真实物理路径
                    // 调整光标到最后
                    quill.setSelection(length + 1)
                } else {
                    this.$message.error('图片插入失败！')
                }
            },
            //下单须知 富文本编辑框图片上传
            quillImgSuccess2(res, file) { // 获取富文本组件实例
                let quill = this.$refs.orderNotice.quill;
                // 如果上传成功
                if (res.success) {
                    // 获取光标所在位置
                    let length = quill.getSelection().index;
                    // 插入图片 res.data为服务器返回的图片地址
                    quill.insertEmbed(length, 'image', 'http://121.37.194.36'+res.data);// 这里的url是图片的访问路径不是真实物理路径
                    // 调整光标到最后
                    quill.setSelection(length + 1)
                } else {
                    this.$message.error('图片插入失败！')
                }
            }
        },
        mounted() {
            this.loadData();
            //发送请求查询部门经理，作为下拉框选项
            this.$http.get("/employee/findAllByJobId/5").then(res => {
                this.managers = res.data
            })
            //发送请求查询上级部门，作为下拉框选项
            this.$http.get("/product/findAllParent/1").then(res => {
                this.parents = res.data
            })
        }
    }

</script>

<style>
    .mydialog{
        width: 70%!important;       /*!important 重要，表示样式的优先级最高  设置模态框宽度 */
    }
    .ql-editor{
        height: 100px!important;    /*设置quill富文本编辑框默认高度*/
    }
    .dialog-footer{
        margin-top: -40px;
    }
</style>